import { submitEditorPwd } from "@/apis/login";
import camera from "@/assets/login/camera.svg";
import defaultPicture from "@/assets/login/personImg.png";
import { phoneReg, psdRegExp, TEXT_PWD_MSG } from "@/common/constant";
import { Encrypt } from "@/common/encryptHelper";
import { getSingleFileArr } from "@/common/fileUtils";
import { sliceUpload } from "@/common/fileUtils/sliceUpload";
import { useGlobalContent } from "@/store";
import { Button, Col, Form, FormInstance, Input, Row, Upload } from "antd";
import { RcFile } from "antd/es/upload";
import { AntDraggableModal, openMessage } from "hy_dev_lib";
import { useState } from "react";
import { ReactSVG } from "react-svg";
import "./index.less";

interface IEditUserInfo {
  open: boolean;
  setOpen: (open: any) => void;
  cb: any;
  form: FormInstance<any>;
}
/** 个人中心弹框 */
const EditUserInfo = (props: IEditUserInfo) => {
  const { open, setOpen, cb, form } = props;
  const { global, globalDispatch } = useGlobalContent();
  const { userInfoData } = global;
  const { tid, tx, mc, sfcg, sfdwzh } = userInfoData;
  const [editorPhoneItemShow, setEditorPhoneItemShow] = useState(false);
  const [editorPwdItenShow, setEditorPwdItenShow] = useState(false);
  const beforeFileUpload = (fileType: string, file: RcFile) => {
    onUploadFile(fileType, file);
    return Upload.LIST_IGNORE;
  };

  const onUploadFile = async (fileType: string, file: RcFile) => {
    await sliceUpload(file, fileType)
      .then((res: any) => {
        if (res.code == 200) {
          let fileData = res.data;
          // 给图片数据添加文件地址
          // console.log(getSingleFileArr(fileData, "dz"));

          globalDispatch({
            type: "userInfoData",
            data: {
              ...userInfoData,
              tx: getSingleFileArr(fileData, "dz")?.[0]?.dz,
            },
          });
        }
      })
      .catch((err: any) => {
        openMessage({
          type: "error",
          content: "上传失败，请重试",
        });
      });
  };

  //点击修改手机号
  const onChangePh = () => {
    setEditorPhoneItemShow(true);
    setEditorPwdItenShow(false);
  };

  //点击修改密码
  const onChangePw = () => {
    setEditorPhoneItemShow(false);
    setEditorPwdItenShow(true);
  };

  //移除readOnly属性
  const removeReadOnly = (value: string) => {
    document.getElementById(value)?.removeAttribute("readonly");
  };

  //修改个人信息弹框的确认按钮
  const onOK = async () => {
    form.validateFields().then(async () => {
      let forgetFormData = form.getFieldsValue();
      const { mmNew, xdh, dh = "", mmOld = "", sjyzm = "" } = forgetFormData;

      let submitMmData = {
        dh: xdh || dh,
        mmNew: Encrypt(mmNew),
        mmOld: Encrypt(mmOld),
      };

      //   if (tx) await submitPersonEditorTXData(tx);
      //   if (forgetFormData?.xdh) await submitPersonEditorFormData(submitPhoneData);
      if (mmNew || xdh) await submitEditorPwd(submitMmData);

      globalDispatch({
        type: "userInfoData",
        data: {
          ...userInfoData,
          dh: forgetFormData?.xdh || userInfoData.dh,
          mm: Encrypt(forgetFormData.mm || userInfoData.mm),
        },
      });

      openMessage({
        type: "success",
        content: "操作成功！",
      });
      cb?.();
      onClose();
    });
  };

  //修改个人信息弹框的关闭按钮
  const onClose = () => {
    setOpen(false);
    setEditorPhoneItemShow(false);
    setEditorPwdItenShow(false);
    form.resetFields();
  };

  return (
    <AntDraggableModal
      destroyOnClose
      title="个人中心"
      maskClosable={false}
      open={!!open}
      onOk={onOK}
      onCancel={onClose}
      width={520}
      centered={true}
      className="editorUserInfo"
      footer={[
        <Button key="sure" type="primary" onClick={onOK}>
          确定
        </Button>,
        <Button key="cancel" onClick={onClose}>
          取消
        </Button>,
      ]}
    >
      <div className="txBox">
        <Upload
          name="avatar"
          accept=".svg,.png,.jpg,.jpeg"
          listType="picture-card"
          className="avatar-uploader bgImg"
          showUploadList={false}
          beforeUpload={(file: RcFile) => beforeFileUpload("tx", file)}
        >
          {tx ? (
            <img
              src={SYSTEM_GLOBAL.fileBaseURL + "/" + tx}
              alt="头像"
              style={{
                width: "100%",
              }}
            />
          ) : (
            <img
              src={defaultPicture}
              alt="头像"
              style={{
                width: "100%",
              }}
            />
          )}

          <div className="mc-style">
            <ReactSVG src={camera}></ReactSVG>
          </div>
        </Upload>
        <div>{mc}</div>
      </div>
      <Form form={form} requiredMark={false} className="personCenterForm">
        <Row gutter={[10, 15]}>
          <Col span={24}>
            <Form.Item labelCol={{ flex: "92px" }} label="姓名" name="mc">
              <Input readOnly allowClear placeholder="姓名" maxLength={11} />
            </Form.Item>
          </Col>
        </Row>
        {!sfcg && !sfdwzh ? (
          <Row gutter={[10, 15]}>
            <Col span={18}>
              <Form.Item labelCol={{ flex: "92px" }} label="手机号" name="dh">
                <Input readOnly allowClear placeholder="手机号" maxLength={11} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Button className="chBtn" onClick={onChangePh} style={{ width: "100%", backgroundColor: "#F2F3F5" }}>
                更换手机号
              </Button>
            </Col>
          </Row>
        ) : (
          <Row gutter={[10, 15]}>
            <Col span={24}>
              <Form.Item labelCol={{ flex: "92px" }} label="手机号" name="dh">
                <Input readOnly allowClear placeholder="手机号" maxLength={11} />
              </Form.Item>
            </Col>
          </Row>
        )}
        <Row gutter={[10, 15]} hidden={!editorPhoneItemShow}>
          <Col span={24}>
            <Form.Item
              labelCol={{ flex: "92px" }}
              label="新手机号"
              name="xdh"
              rules={[
                { required: editorPhoneItemShow ? true : false, message: "新手机号必填" },
                { pattern: phoneReg, message: "手机号格式不正确" },
              ]}
            >
              <Input allowClear placeholder="手机号" maxLength={11} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={[10, 15]}>
          <Col span={18}>
            <Form.Item label="密码" labelCol={{ flex: "92px" }} name="mmOld">
              <Input.Password type="password" readOnly maxLength={12} />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Button onClick={onChangePw} style={{ width: "100%", backgroundColor: "#F2F3F5" }}>
              修改密码
            </Button>
          </Col>
        </Row>
        <Row gutter={[10, 15]} hidden={!editorPwdItenShow}>
          <Col span={24}>
            <Form.Item
              labelCol={{ flex: "92px" }}
              label="新密码"
              name="mmNew"
              rules={[
                {
                  required: editorPwdItenShow ? true : false,
                  pattern: psdRegExp,
                  message: TEXT_PWD_MSG,
                },
              ]}
            >
              <Input.Password
                allowClear
                placeholder="新密码"
                maxLength={18}
                id="mmNew"
                type="password"
                readOnly
                onFocus={() => removeReadOnly("mmNew")}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={[10, 15]} hidden={!editorPwdItenShow}>
          <Col span={24}>
            <Form.Item
              label="确认新密码"
              name="cfmm"
              rules={[
                {
                  required: editorPwdItenShow ? true : false,
                  validator: (_, value) => {
                    if (!editorPwdItenShow) return Promise.resolve();
                    if (psdRegExp.test(value)) {
                      if (value !== form.getFieldValue("mmNew")) return Promise.reject("两次密码不一致");

                      return Promise.resolve();
                    }

                    return Promise.reject(new Error(TEXT_PWD_MSG));
                  },
                },
              ]}
            >
              <Input.Password
                id="againNewPwd"
                type="password"
                readOnly
                onFocus={() => removeReadOnly("againNewPwd")}
                allowClear
                placeholder="确认新密码"
                maxLength={18}
              />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </AntDraggableModal>
  );
};

export default EditUserInfo;
